package com.dotstone.chipism.view;

import java.util.ArrayList;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.Room;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;
import com.dotstone.chipism.listener.onReachTopListener;

public class CicleGroupLayout extends ViewGroup {
	private int mRadius;
	/**
	 * 该容器内child item的默认尺寸
	 */
	private static final float RADIO_DEFAULT_CHILD_DIMENSION = 1 / 3f;
	/**
	 * 该容器的内边距,无视padding属性，如需边距请用该变量
	 */
	// private static final float RADIO_PADDING_LAYOUT = 1 / 48f;
	private static final float RADIO_PADDING_LAYOUT = 0;

	/**
	 * 如果移动角度达到该值，则屏蔽点击
	 */
	private static final int NOCLICK_VALUE = 3;

	/**
	 * 该容器的内边距,无视padding属性，如需边距请用该变量
	 */
	private float mPadding;
	/**
	 * 布局时的开始角度
	 */
	private double mStartAngle = -90;
	private double currentStartAngle;
	/**
	 * 菜单项的文本
	 */
	private List<Room> mRooms = new CopyOnWriteArrayList<Room>();
	private List<Room> mShowRooms = new CopyOnWriteArrayList<Room>();
	private List<Room> mHideRooms = new CopyOnWriteArrayList<Room>();
	private long lastChange = 0;
	// private List<Group> mGroups;
	private int head;
	private int tail;
	private boolean clockwise;
	/**
	 * 检测按下到抬起时旋转的角度
	 */
	private float mTmpAngle;
	/**
	 * 检测按下到抬起时使用的时间
	 */
	// private long mDownTime;
	private List<View> views = new ArrayList<View>();
	/**
	 * 判断是否正在自动滚动
	 */
	// private boolean isFling;
	private int centerX;
	private int centerY;
	private int l;
	private float angleDelay;
	private int topPosition;

	public CicleGroupLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		// 无视padding
		setPadding(0, 0, 0, 0);
	}

	/**
	 * 设置布局的宽高，并策略menu item宽高
	 */
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int resWidth = 0;
		int resHeight = 0;
		/**
		 * 根据传入的参数，分别获取测量模式和测量值
		 */
		int width = MeasureSpec.getSize(widthMeasureSpec);
		int widthMode = MeasureSpec.getMode(widthMeasureSpec);

		int height = MeasureSpec.getSize(heightMeasureSpec);
		int heightMode = MeasureSpec.getMode(heightMeasureSpec);
		/**
		 * 如果宽或者高的测量模式非精确值
		 */
		if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY) {
			// 主要设置为背景图的高度
			resWidth = getSuggestedMinimumWidth();
			// 如果未设置背景图片，则设置为屏幕宽高的默认值
			resWidth = resWidth == 0 ? getDefaultWidth() : resWidth;

			resHeight = getSuggestedMinimumHeight();
			// 如果未设置背景图片，则设置为屏幕宽高的默认值
			resHeight = resHeight == 0 ? getDefaultWidth() : resHeight;
		} else {
			// 如果都设置为精确值，则直接取小值；
			resWidth = resHeight = Math.min(width, height);
		}
		setMeasuredDimension(resWidth, resHeight);
		// 获得半径
		mRadius = Math.max(getMeasuredWidth(), getMeasuredHeight());
		// menu item数量
		final int count = getChildCount();
		// menu item尺寸
		int childSize = (int) (mRadius * RADIO_DEFAULT_CHILD_DIMENSION);
		// menu item测量模式
		int childMode = MeasureSpec.UNSPECIFIED;
		// 迭代测量
		for (int i = 0; i < count; i++) {
			final View child = getChildAt(i);
			// 计算menu item的尺寸；以及和设置好的模式，去对item进行测量
			int makeMeasureSpec = -1;
			makeMeasureSpec = MeasureSpec.makeMeasureSpec(childSize, childMode);
			child.measure(makeMeasureSpec, makeMeasureSpec);
		}
		mPadding = RADIO_PADDING_LAYOUT * mRadius;
	}

	/**
	 * MenuItem的点击事件接口
	 * 
	 * @author zhy
	 * 
	 */
	public interface OnMenuItemClickListener1 {
		void itemClick(String id);
	}

	/**
	 * view的中间角度为270.0 说明该view处于最顶端 调用接口 让监听该接口的Activity改变外圈数据
	 */

	private onReachTopListener onReachTopListener;
	private OnAddRoomListener onAddRoomListener;

	public void setOnReachTopListener(onReachTopListener onReachTopListener) {
		this.onReachTopListener = onReachTopListener;
	}

	public void setOnAddRoomListener(OnAddRoomListener onAddRoomListener) {
		this.onAddRoomListener = onAddRoomListener;
	}

	public interface OnAddRoomListener {
		void addClick();
	}

	/**
	 * MenuItem的点击事件接口
	 */
	private OnMenuItemClickListener1 mOnMenuItemClickListener;

	/**
	 * 设置MenuItem的点击事件接口
	 * 
	 * @param mOnMenuItemClickListener
	 */
	public void setOnMenuItemClickListener(OnMenuItemClickListener1 mOnMenuItemClickListener) {
		this.mOnMenuItemClickListener = mOnMenuItemClickListener;
	}

	public void updateChildView(final int i) {
		TextView tv = (TextView) views.get(i).findViewById(R.id.id_circle_menu_item_text);

		if (tv != null) {
			tv.setVisibility(View.VISIBLE);
			switch (mShowRooms.get(i).getStatus()) {
			case 9:
				tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
				tv.setTextColor(Color.WHITE);
				break;
			case 1:
				tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
				tv.setTextColor(Color.parseColor("#9edffe"));
				break;
			default:
				break;
			}
			tv.setText(mShowRooms.get(i).getRoomName());
			tv.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {

					if (mOnMenuItemClickListener != null) {
						mOnMenuItemClickListener.itemClick(mShowRooms.get(i).getRoomId());
					}
				}
			});
		}
	}

	/**
	 * 设置menu item的位置
	 */
	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		int layoutRadius = mRadius;
		centerX = mRadius / 2;
		centerY = mRadius / 2;

		// Log.i("wmy", "blue"+layoutRadius+" "+getWidth()+" "+ );
		final int childCount = getChildCount();
		// Log.i("wmy", "242蓝圈中有" + childCount + "个子控件");
		int left, top;
		// menu item 的尺寸
		int cWidth = (int) (layoutRadius * RADIO_DEFAULT_CHILD_DIMENSION);
		// 根据menu item的个数，计算角度
		if (getChildCount() != 0) {
			angleDelay = 360 / getChildCount();
		} else {
			angleDelay = 360;
		}
		// 遍历去设置menuitem的位置
		for (int i = 0; i < childCount; i++) {
			final View child = getChildAt(i);
			mStartAngle %= 360;
			if (mStartAngle < 0) {
				currentStartAngle = 360 + mStartAngle;
			} else {
				currentStartAngle = mStartAngle;
			}
			// Log.i("wmy", i + " currentStartAngle = " + currentStartAngle);
			if (currentStartAngle == 270.0) { // 该view为最高点 调用接口
				if (i <= mShowRooms.size() && i != mShowRooms.size()) {
					topPosition = i;
				}
			}
			if (currentStartAngle == 90.0) {
				if (mRooms.size() >= 8 && i != 7) {
					// Log.i("wmy",
					// "滑到最底层的item"+mShowRooms.get(i).getRoomName());
					// if (clockwise) { // 顺时针
					// mHideRooms.add(mShowRooms.get(i));
					// mShowRooms.remove(i);
					// mShowRooms.add(i, mHideRooms.get(0));
					// mHideRooms.remove(0);
					// resetContent(i);
					// for (Room r1 : mShowRooms) {
					// // Log.i("wmy", "");
					// }
					// for (Room r2 : mHideRooms) {
					// // Log.i("wmy", "");
					// }
					// } else { // 逆时针
					// mHideRooms.add(0, mShowRooms.get(i));
					// mShowRooms.remove(i);
					// mShowRooms.add(i, mHideRooms.get(mHideRooms.size() - 1));
					// mHideRooms.remove(mHideRooms.size() - 1);
					// resetContent(i);
					// }
//					Log.i("circle", "滑到最底层的item " + i + " " + mShowRooms.get(i).getRoomName());
					if (System.currentTimeMillis() - lastChange > 200) {
						lastChange = System.currentTimeMillis();
						if (clockwise) { // 顺时针
							mHideRooms.add(mShowRooms.get(i));
							// Log.i("circle", "移除" +
							// mShowScenes.get(i).getSceneName());
							mShowRooms.remove(i);
							mShowRooms.add(i, mHideRooms.get(0));
							// Log.i("circle", "添加" +
							// mShowScenes.get(i).getSceneName());
							mHideRooms.remove(0);
						} else { // 逆时针
							mHideRooms.add(0, mShowRooms.get(i));
							// Log.i("circle", "移除" +
							// mShowScenes.get(i).getSceneName());
							mShowRooms.remove(i);
							mShowRooms.add(i, mHideRooms.get(mHideRooms.size() - 1));
							// Log.i("circle", "添加" +
							// mShowScenes.get(i).getSceneName());
							mHideRooms.remove(mHideRooms.size() - 1);
						}
//						 for(Room r1:mShowRooms){
//						 Log.e("circle", "显示的组别 = "+r1.getRoomName());
//						 }
//						 for(Room r2:mHideRooms){
//						 Log.w("circle", "隐藏的组别 = "+r2.getRoomName());
//						 }
						resetContent(i);
					} else {

					}
				}
			}
			// 计算，中心点到menu item中心的距离
			float tmp = layoutRadius / 2f - cWidth / 2 - mPadding;
			// tmp cosa 即menu item中心点的横坐标
			left = layoutRadius / 2
					+ (int) Math.round(tmp * Math.cos(Math.toRadians(currentStartAngle)) - 1 / 2f * cWidth);
			// tmp sina 即menu item的纵坐标
			top = layoutRadius / 2
					+ (int) Math.round(tmp * Math.sin(Math.toRadians(currentStartAngle)) - 1 / 2f * cWidth);

			child.layout(left, top, left + cWidth, top + cWidth);
			// 叠加尺寸
			mStartAngle += angleDelay;
		}

	}

	public int getTopPosition() {
		return topPosition;
	}

	public String getTopId() {
		if (topPosition != 9 && topPosition < mShowRooms.size()) {
			return mShowRooms.get(topPosition).getRoomId();
		} else {
			return "-1";
		}
	}

	/**
	 * 记录上一次的x，y坐标
	 */
	private float mLastX;
	private float mLastY;
	private long downTime;
	private long upTime;

	/**
	 * 自动滚动的Runnable
	 */
	// private AutoFlingRunnable mFlingRunnable;

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		float x = event.getX();
		float y = event.getY();
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			mLastX = x;
			mLastY = y;
			mTmpAngle = 0;
			l = getL(x, y);
			if (l > mRadius / 2) {
				return false;
			}
			topPosition = 9;
			downTime = System.currentTimeMillis();
			break;
		case MotionEvent.ACTION_MOVE:
			/**
			 * 获得开始的角度
			 */
			float start = getAngle(mLastX, mLastY);
			/**
			 * 获得当前的角度
			 */
			float end = getAngle(x, y);
			// Log.i("wmy", "start = "+start+" end = "+end);
			l = getL(x, y);
			if (l > mRadius / 2) {
				return false;
			}
			if (getQuadrant(x, y) == 1 || getQuadrant(x, y) == 4) {
				mStartAngle += end - start;
				mTmpAngle += end - start;
				// Log.i("wmy", "1 4象限");
				if (end < start) {
					// Log.i("wmy", "逆时针");
					clockwise = false;
				} else {
					// Log.i("wmy", "顺时针");
					clockwise = true;
				}
			} else {
				// 二、三象限，色角度值是付值
				mStartAngle += start - end;
				mTmpAngle += start - end;
				// Log.i("wmy", "2 3象限");
				if (end < start) {
					// Log.i("wmy", "顺时针");
					clockwise = true;
				} else {
					// Log.i("wmy", "逆时针");
					clockwise = false;
				}
			}
			// 重新布局
			requestLayout();
			mLastX = x;
			mLastY = y;
			break;
		case MotionEvent.ACTION_UP:

			// 计算，每秒移动的角度
			// Log.e("wmy", "手势上提");
			// 当手势上抬时 停止转盘转动
			// 获取views.get(0)的角度
			// 判断该控件的初始角与45度的余值
			// 让其产生回弹效果 弹回中间位置
			// 判断哪个控件属于最顶端的位置 调用接口
			upTime = System.currentTimeMillis();
			adjustArea();
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					if (onReachTopListener != null && topPosition != 9) {
						onReachTopListener.reach(mShowRooms.get(topPosition).getRoomId());
						resetContent(9);
						Log.i("circle", "组别手势抬起 = " + mShowRooms.get(topPosition).getRoomId());
					}else{
						onReachTopListener.reach("");
					}
				}
			}, 100);
			l = getL(x, y);
			if (l > mRadius / 2) {
				return false;
			}

			// 如果当前旋转角度超过NOCLICK_VALUE屏蔽点击
			if (Math.abs(mTmpAngle) > NOCLICK_VALUE) {
				// Log.i("wmy", "屏蔽点击");
				return true;
			}
			break;
		}
		return super.dispatchTouchEvent(event);
	}

	Handler mHandler = new Handler();

	private void resetContent(int p) {
		if (mShowRooms.size() < 8) {
			for (int i = 0; i < mShowRooms.size(); i++) {
				TextView tv1 = (TextView) views.get((i)).findViewById(R.id.id_circle_menu_item_text);
				tv1.setText(mShowRooms.get(i).getRoomName());
			}
		} else {
			for (int i = 0; i < 7; i++) {
				TextView tv1 = (TextView) views.get((i)).findViewById(R.id.id_circle_menu_item_text);
				tv1.setText(mShowRooms.get(i).getRoomName());
			}
		}
	}

	/**
	 * 主要为了action_down时，返回true
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return true;
	}

	private void adjustArea() {
		double differ = mStartAngle % 45;
		// System.out.println("differ = " + differ);
		if (differ < 45 / 2) {
			mStartAngle -= differ;
		} else {
			mStartAngle += (45 - differ);
		}
		if (upTime - downTime > 100) {
			requestLayout();
			Log.i("wmy", "需要回弹");
			// invalidate();
		} else {
			Log.i("wmy", "不需要回弹");
		}
	}

	/**
	 * 根据触摸的位置，计算角度
	 * 
	 * @param xTouch
	 * @param yTouch
	 * @return
	 */
	private float getAngle(float xTouch, float yTouch) {
		double x = xTouch - (mRadius / 2d);
		double y = yTouch - (mRadius / 2d);
		return (float) (Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI);
	}

	/**
	 * 根据当前位置计算象限
	 * 
	 * @param x
	 * @param y
	 * @return
	 */
	private int getQuadrant(float x, float y) {
		int tmpX = (int) (x - mRadius / 2);
		int tmpY = (int) (y - mRadius / 2);
		if (tmpX >= 0) {
			return tmpY >= 0 ? 4 : 1;
		} else {
			return tmpY >= 0 ? 3 : 2;
		}
	}

	/**
	 * 设置菜单条目的图标和文本
	 * 
	 * @param resIds
	 */
	public void setRooms(List<Room> mRooms) {
		this.mRooms = mRooms;
		Log.e("wmy", "setRooms = " + mRooms.size());
		// 获取了传进来的情景集合
		// 将其对应到每个view上
		setInView();
	}

	private void setInView() {
		if (mRooms.size() != 0) {
			if (mRooms.size() < 8) {
				mShowRooms = mRooms;
				for (int i = 0; i < mShowRooms.size(); i++) {
					TextView tv = (TextView) views.get((i)).findViewById(R.id.id_circle_menu_item_text);
					tv.setText(mShowRooms.get(i).getRoomName());
				}
				TextView tv = (TextView) views.get(mShowRooms.size()).findViewById(R.id.id_circle_menu_item_text);
				tv.setText("+");
				for (int i = mShowRooms.size() + 1; i < 8; i++) {
					TextView tv1 = (TextView) views.get((i)).findViewById(R.id.id_circle_menu_item_text);
					tv1.setText("");
				}
			} else {
				mShowRooms.clear();
				for (int i = 0; i < 7; i++) {
					TextView tv = (TextView) views.get((i)).findViewById(R.id.id_circle_menu_item_text);
					tv.setText(mRooms.get(i).getRoomName());
					mShowRooms.add(mRooms.get(i));
				}
//				mShowRooms = mRooms.subList(0, 7);
				TextView tv = (TextView) views.get(7).findViewById(R.id.id_circle_menu_item_text);
				tv.setText("+");
				mHideRooms.clear();
				for (int i = 7; i < mRooms.size(); i++) {
					mHideRooms.add(mRooms.get(i));
				}
//				mHideRooms.clear();
//				mHideRooms.addAll(mRooms.subList(7, mRooms.size()));
//				head = 0;
//				tail = 7;
				 Log.e("wmy", "mHideRooms.size() = "+mHideRooms.size());
			}
		} else {
			TextView tv = (TextView) views.get(0).findViewById(R.id.id_circle_menu_item_text);
			tv.setText("+");
		}
	}

	public void addMenus() {
		removeAllViews();
		mHideRooms.clear();
		mShowRooms.clear();
		mRooms.clear();
		mStartAngle = -90;
		LayoutInflater mInflater = LayoutInflater.from(getContext());
		/**
		 * 根据用户设置的参数，初始化view
		 */
		for (int i = 0; i < 8; i++) {
			final int j = i;
			View view = mInflater.inflate(R.layout.circle_menu_item1, this, false);
			final TextView tv = (TextView) view.findViewById(R.id.id_circle_menu_item_text);
			tv.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View view) {
					// TODO Auto-generated method stub
					// Log.i("wmy", "tv.getTag() = " + tv.getTag());
					if (mOnMenuItemClickListener != null && mRooms.size() > j) {
						if (j == 7) {

						} else {
							mOnMenuItemClickListener.itemClick(mShowRooms.get(j).getRoomId());
							// Log.i("wmy", "j = " + j);
						}
						if (tv.getText().toString().equals("+")) {
							onAddRoomListener.addClick();
						}
					}
					if (tv.getText().toString().equals("+")) {
						// Log.i("wmy", "点击了 添加 ");
						onAddRoomListener.addClick();
					}
				}
			});
			view.setTag(i);
			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View view) {
					// TODO Auto-generated method stub
					// Log.i("wmy", "view.getTag() = " + view.getTag());
					if (mOnMenuItemClickListener != null && mRooms.size() > j) {
						if (j == 7) {
							onAddRoomListener.addClick();
						} else {
							mOnMenuItemClickListener.itemClick(mShowRooms.get(j).getRoomId());
							// Log.i("wmy", "j = " + j);
						}
					}
				}
			});
			addView(view);
			views.add(view);
		}

	}

	/**
	 * 获得默认该layout的尺寸
	 * 
	 * @return
	 */
	private int getDefaultWidth() {
		WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics outMetrics = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(outMetrics);
		return Math.min(outMetrics.widthPixels, outMetrics.heightPixels);
	}

	private int getL(float x, float y) {
		l = (int) (Math.sqrt(Math.pow(Math.abs(x - centerX), 2) + Math.pow(Math.abs(y - centerY), 2)));
		return l;
	}

}